package com.example.stock.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ObjectUtil;
import com.example.stock.entity.Stock;
import com.example.stock.tencent.DingDingBot;
import com.example.stock.tencent.StockBean;
import com.example.stock.tencent.TencentProxy;
import com.example.stock.util.HolidayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author tanlvxu
 * @Date 2025/1/9 13:45
 * @Description TODO
 */
@Service
public class LiangBiService {

    @Autowired
    private IStockService stockService;

    @Autowired
    private TencentProxy tencentProxy;
    public String getLastGzr(LocalDateTime nowLocal) throws ParseException {
        String calcDate = null;
        for (int i = 1; i < 10; i++) {
            nowLocal = nowLocal.plusDays(-1);
            // 定义日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            // 格式化当前时间
            String formattedNow = nowLocal.format(formatter);
            String workingDay = HolidayUtil.isWorkingDay(formattedNow);
            if("0".equals(workingDay)){
                calcDate =  formattedNow;
                break;
            }
        }
        return calcDate;
    }

//    @PostConstruct
    public void test() throws ParseException {
        List<StockBean> stocks = tencentProxy.getData();
        LocalDateTime nowLocal =  LocalDateTime.now();
        String lastGzr = getLastGzr(nowLocal);
//        String lastGzr2 = getLastGzr(LocalDateTime.parse(lastGzr, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    //    List<Stock> stocks = stockService.listByCalcTimeAndCalcType(lastGzr, 3);
        List<Stock> stocks2 = stockService.listByCalcTimeAndCalcType(lastGzr, 3);

        String lastGzr3 = getLastGzr(LocalDateTime.parse(lastGzr, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        String lastGzr4 = getLastGzr(LocalDateTime.parse(lastGzr, DateTimeFormatter.ofPattern("yyyy-MM-dd")));

        List<StockBean> resStock = new ArrayList<>();
        //不是涨停
        Map<String, StockBean> stockMap = stocks.stream().filter(obj -> obj.getHighLimit() > 0 && ObjectUtil.notEqual(obj.getHighLimit() , obj.getPriceNow())).collect(Collectors.toMap(StockBean::getCode, Function.identity()));
        Map<String, Stock> stock2Map = stocks2.stream().filter(obj -> obj.getHighLimit() > 0 && ObjectUtil.notEqual(obj.getHighLimit() , obj.getPriceNow())).collect(Collectors.toMap(Stock::getCode, Function.identity()));
        stockMap.forEach((key, stock)->{
            Stock stock2 = stock2Map.get(key);
            if(stock.getVolumeCompare() > 4* stock2.getVolumeCompare() && stock.getChangePercent() >= 3 && stock.getChangePercent() <= 6){
                System.out.println(stock);
            }
        });
    }


    private boolean isJiaoyiDay() throws ParseException {
        // 获取当前时间
        LocalDateTime nowLocal = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 格式化当前时间
        String formattedNow = nowLocal.format(formatter);
        String workingDay = HolidayUtil.isWorkingDay(formattedNow);
        if(!"0".equals(workingDay)){
            Console.log(formattedNow+"不是工作日不处理refresh3");
            return false;
        }
        return true;
    }

    //指标 2
    @Scheduled(cron = "30 54 14 * * 1-5")
    public void test2() throws ParseException {
        if(!isJiaoyiDay()){
            return ;
        }
        //String[] testDates = new String[]{"2024-12-23", "2024-12-24", "2024-12-25", "2024-12-26", "2024-12-27","2024-12-30", "2024-12-31", "2025-01-02","2025-01-03","2025-01-06","2025-01-07","2025-01-08","2025-01-09"};

//        for (int i = 0; i < testDates.length; i++) {
            String lastGzr = getConversionDateMM(new Date());
            List<StockBean> stock2222s = tencentProxy.getData().stream().filter(obj -> obj.getHighLimit() > 0 && ObjectUtil.notEqual(obj.getHighLimit() , obj.getPriceNow())).collect(Collectors.toList());
            List<Stock> stocks3 = new ArrayList<>();
            for (int i = 0; i < stock2222s.size(); i++) {
                Stock stock = new Stock();
                BeanUtil.copyProperties(stock2222s.get(i), stock);
                stocks3.add(stock);
            }
//        List<Stock> stocks3 = stockService.listByCalcTimeAndCalcType(lastGzr, 3);

//        Map<String, Stock> stock3Map = stocks3.stream().collect(Collectors.toMap(Stock::getCode, Function.identity()));
            String lastGzr2 = getLastGzr(LocalDate.parse(lastGzr, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay());
            System.out.println();
            System.out.println();
            System.out.println();

            List<Stock> stocks = stocks3; //stockService.listByCalcTimeAndCalcType(lastGzr2, 3);
            List<Stock> stocks2 = stockService.listByCalcTimeAndCalcType(lastGzr2, 3);
            String lastGzr4 = getLastGzr(LocalDate.parse(lastGzr2, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay());
            List<Stock> stocks4 = stockService.listByCalcTimeAndCalcType(lastGzr4, 3);
            Map<String, Stock> stock4Map = stocks4.stream().collect(Collectors.toMap(Stock::getCode, Function.identity()));
            List<Stock> resStock = new ArrayList<>();
            StringBuffer stringBuffer = new StringBuffer("当日系统股如下：\n");
            System.out.println(("计算日*****************************************-" + lastGzr + "计算日-" + lastGzr2 + "计算日-" + lastGzr4));
            //不是涨停
            Map<String, Stock> stockMap = stocks.stream().filter(obj -> obj.getHighLimit() > 0 && obj.getHighLimit() != obj.getPriceNow()).collect(Collectors.toMap(Stock::getCode, Function.identity()));
            Map<String, Stock> stock2Map = stocks2.stream().filter(obj -> obj.getHighLimit() > 0 && obj.getHighLimit() != obj.getPriceNow()).collect(Collectors.toMap(Stock::getCode, Function.identity()));
            stockMap.forEach((key, stock)->{
                Stock stock2 = stock2Map.get(key);
                Stock stock4 = stock4Map.get(key);
                Double curVolumeCompare = stock.getVolumeCompare() + 0.1 ;
                if(stock2 != null && stock4 != null) {// && stock.getPriceMin()>stock2.getPriceNow()
                    if (
                            ObjectUtil.notEqual(stock2.getHighLimit(), stock2.getPriceNow())
                                    && stock.getExchange() > 5 && stock2.getExchange() > 5 && ObjectUtil.notEqual(stock.getHighLimit(), stock.getPriceNow())

                                    && curVolumeCompare > 2 * stock2.getVolumeCompare() && curVolumeCompare < 3.5 * stock2.getVolumeCompare()
                                    && !stock.getName().contains("ST")
                                    && ((stock.getHighLimit() - stock2.getPriceNow()) / stock2.getPriceNow() < 0.11) && stock.getChangePercent() < 6 && stock.getChangePercent() > 3
                                    && curVolumeCompare > 2 * stock4.getVolumeCompare()  //&&
                                    && stock.getAmplitude() >= stock2.getAmplitude()  &&  stock.getAmplitude() >= stock4.getAmplitude()
                                    && stock.getChangePercent() + stock2.getChangePercent() + stock4Map.get(key).getChangePercent() > 0
                    ) {

                        String title = "";
                        // if(stock.getPriceMin()< stock2.getPriceNow() && stock.getPriceNow() > stock2.getPriceNow() && stock4Map.get(key).getPriceNow() > stock2.getPriceNow()) {
                        // if(stock4Map.get(key).getVolumeCompare()< stock2.getVolumeCompare()  && stock2.getChangePercent() > stock4Map.get(key).getChangePercent() && ( stock.getExchange()>5) && stock.getPriceMin() >= stock2.getPriceNow()) {
                        //   if(stock2.getInPan() < stock2.getOutPan() && stock.getInPan()  < stock.getOutPan()) {//stock.getPriceNow() <= stock.getPriceAvg() &&                         && (stock.getOutPan() -stock.getInPan() > stock2.getOutPan() -stock2.getInPan())
                        if (curVolumeCompare < 3 * stock4.getVolumeCompare()) {
                            stringBuffer.append("精选推荐 ：" + stock.getName() + "-" + stock.getCode() + "\n");
                        } else {
                            stringBuffer.append("一般推荐 ：" + stock.getName() + "-" + stock.getCode() + "\n");
                        }
                        //   }
//                //    }
//                    double profit = (((stock3Map.get(key).getPriceMax() - stock.getPriceNow()) / stock.getPriceNow()) * 100);
//                    if(profit > 5){
//                        title = lastGzr + "****"+title;
//                    }

                        System.out.println(title + "量比" + (curVolumeCompare / stock2.getVolumeCompare()) + "---" + stock.getName());
                    }
                }
            });
//        }
        DingDingBot.send(stringBuffer.toString());
    }

    //指标3
    public void test3() throws ParseException {

        String[] testDates = new String[]{"2024-12-23", "2024-12-24", "2024-12-25", "2024-12-26", "2024-12-27","2024-12-30", "2024-12-31", "2025-01-02","2025-01-03","2025-01-06","2025-01-07","2025-01-08"};

        for (int i = 0; i < testDates.length; i++) {
            String lastGzr = testDates[i];

            List<Stock> stocks3 = stockService.listByCalcTimeAndCalcType(lastGzr, 3);
            Map<String, Stock> stock3Map = stocks3.stream().collect(Collectors.toMap(Stock::getCode, Function.identity()));
            String lastGzr2 = getLastGzr(LocalDate.parse(lastGzr, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay());
            String lastGzr3 = getLastGzr(LocalDate.parse(lastGzr2, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay());
            System.out.println();
            System.out.println();
            System.out.println();
            System.out.println(("计算日*****************************************-" + lastGzr + "计算日-" + lastGzr2 + "计算日-" + lastGzr3));
            List<Stock> stocks = stockService.listByCalcTimeAndCalcType(lastGzr2, 3);
            List<Stock> stocks2 = stockService.listByCalcTimeAndCalcType(lastGzr3, 3);
            String lastGzr4 = getLastGzr(LocalDate.parse(lastGzr3, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay());
            List<Stock> stocks4 = stockService.listByCalcTimeAndCalcType(lastGzr4, 3);
            Map<String, Stock> stock4Map = stocks4.stream().collect(Collectors.toMap(Stock::getCode, Function.identity()));
            List<Stock> resStock = new ArrayList<>();
            //不是涨停
            Map<String, Stock> stockMap = stocks.stream().filter(obj -> obj.getHighLimit() > 0 && obj.getHighLimit() != obj.getPriceNow()).collect(Collectors.toMap(Stock::getCode, Function.identity()));
            Map<String, Stock> stock2Map = stocks2.stream().filter(obj -> obj.getHighLimit() > 0 && obj.getHighLimit() != obj.getPriceNow()).collect(Collectors.toMap(Stock::getCode, Function.identity()));
            stockMap.forEach((key, stock)->{
                Stock stock2 = stock2Map.get(key);
                Stock stock4 = stock4Map.get(key);
                if(stock.getExchange() > 5  && stock2.getExchange() > 5 && stock.getPriceMin()>stock2.getPriceNow() && ObjectUtil.notEqual(stock.getHighLimit(),stock.getPriceNow())  && stock.getVolumeCompare() > 2* stock2.getVolumeCompare() && stock.getVolumeCompare() < 3* stock2.getVolumeCompare()
                        && !stock.getName().contains("ST") && ((stock.getHighLimit() - stock2.getPriceNow())/stock2.getPriceNow() <0.11) && stock.getChangePercent()<6 && stock.getChangePercent()>3
                        && stock.getVolumeCompare() > 2* stock4.getVolumeCompare()
                ){

                    String title = "";
                    if(stock.getVolumeCompare() < 3* stock4.getVolumeCompare()){
                        title = "精选";
                    }

//                    if(stock.getPriceMin()< stock2.getPriceNow() && stock.getPriceNow() > stock2.getPriceNow() && stock4Map.get(key).getPriceNow() > stock2.getPriceNow()) {
//                        // if(stock4Map.get(key).getVolumeCompare()< stock2.getVolumeCompare()  && stock2.getChangePercent() > stock4Map.get(key).getChangePercent() && ( stock.getExchange()>5) && stock.getPriceMin() >= stock2.getPriceNow()) {
//                        //   if(stock2.getInPan() < stock2.getOutPan() && stock.getInPan()  < stock.getOutPan()) {//stock.getPriceNow() <= stock.getPriceAvg() &&                         && (stock.getOutPan() -stock.getInPan() > stock2.getOutPan() -stock2.getInPan())
//
//                        //   }
////                    }
//                    }
                    double profit = (((stock3Map.get(key).getPriceMax() - stock.getPriceNow()) / stock.getPriceNow()) * 100);
                    if(profit > 5){
                        title = lastGzr + "****"+title;
                    }
                    System.out.println(title+"量比"+(stock.getVolumeCompare()/stock2.getVolumeCompare())+"盈利" + profit + "---" + stock.getName());
                }
            });
        }

    }

    public String getLiangBi() throws ParseException {
        // 获取当前时间
        LocalDateTime nowLocal =  LocalDateTime.now();
        String lastGzr = getLastGzr(nowLocal);
        String lastGzr2 = getLastGzr(LocalDateTime.parse(lastGzr, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        List<Stock> stocks = stockService.listByCalcTimeAndCalcType(lastGzr, 3);
        List<Stock> stocks2 = stockService.listByCalcTimeAndCalcType(lastGzr2, 3);
        List<Stock> resStock = new ArrayList<>();
        //不是涨停
        Map<String, Stock> stockMap = stocks.stream().filter(obj -> obj.getHighLimit() > 0 && obj.getHighLimit() != obj.getPriceNow()).collect(Collectors.toMap(Stock::getCode, Function.identity()));
        Map<String, Stock> stock2Map = stocks2.stream().filter(obj -> obj.getHighLimit() > 0 && obj.getHighLimit() != obj.getPriceNow()).collect(Collectors.toMap(Stock::getCode, Function.identity()));
        stockMap.forEach((key, stock)->{
            Stock stock2 = stock2Map.get(key);
            if(stock.getVolumeCompare() > 4* stock.getVolumeCompare() && stock2.getChangePercent() >= 3 && stock2.getChangePercent() <= 6 && stock.getChangePercent() < stock2.getChangePercent()){
                resStock.add(stock);
            }
        });

        return lastGzr;
    }


    public static String getConversionDateMM(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(date);
        return format;
    }


    //指标 2
//    @PostConstruct
    public void test4() throws ParseException {

        String[] testDates = new String[]{ "2025-02-11","2025-02-12","2025-02-13","2025-02-14","2025-02-17","2025-02-18","2025-02-19"};


        for (int i = 0; i < testDates.length; i++) {
            String lastGzr = testDates[i];

            List<Stock> stocks3 = stockService.listByCalcTimeAndCalcType(lastGzr, 3);
            Map<String, Stock> stock3Map = stocks3.stream().collect(Collectors.toMap(Stock::getCode, Function.identity()));
            String lastGzr2 = getLastGzr(LocalDate.parse(lastGzr, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay());
            String lastGzr3 = getLastGzr(LocalDate.parse(lastGzr2, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay());
            System.out.println();
            System.out.println();
            System.out.println();
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("计算日*****************************************-" + lastGzr + "计算日-" + lastGzr2 + "计算日-" + lastGzr3+"\n");
            System.out.println(("计算日*****************************************-" + lastGzr + "计算日-" + lastGzr2 + "计算日-" + lastGzr3));
            List<Stock> stocks = stockService.listByCalcTimeAndCalcType(lastGzr2, 3);
            List<Stock> stocks2 = stockService.listByCalcTimeAndCalcType(lastGzr3, 3);
            String lastGzr4 = getLastGzr(LocalDate.parse(lastGzr3, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay());
            List<Stock> stocks4 = stockService.listByCalcTimeAndCalcType(lastGzr4, 3);
            Map<String, Stock> stock4Map = stocks4.stream().collect(Collectors.toMap(Stock::getCode, Function.identity()));
            List<Stock> resStock = new ArrayList<>();
            //不是涨停
            Map<String, Stock> stockMap = stocks.stream().filter(obj -> obj.getHighLimit() > 0 && obj.getHighLimit() != obj.getPriceNow()).collect(Collectors.toMap(Stock::getCode, Function.identity()));
            Map<String, Stock> stock2Map = stocks2.stream().filter(obj -> obj.getHighLimit() > 0 && obj.getHighLimit() != obj.getPriceNow()).collect(Collectors.toMap(Stock::getCode, Function.identity()));
            stockMap.forEach((key, stock)->{
                Stock stock2 = stock2Map.get(key);
                Stock stock4 = stock4Map.get(key); // && stock.getPriceMin()>stock2.getPriceNow()
                Double curVolumeCompare = stock.getVolumeCompare() + 0.05 ;
                if(stock.getExchange() > 5  && stock2.getExchange() > 5 && ObjectUtil.notEqual(stock.getHighLimit(),stock.getPriceNow())
                        && ObjectUtil.notEqual(stock2.getHighLimit(),stock2.getPriceNow())
                        && curVolumeCompare > 2* stock2.getVolumeCompare() && curVolumeCompare < 3.5* stock2.getVolumeCompare()
                        && !stock.getName().contains("ST") && ((stock.getHighLimit() - stock2.getPriceNow())/stock2.getPriceNow() <0.11) && stock.getChangePercent()<6 && stock.getChangePercent()>3
                        && curVolumeCompare > 2* stock4.getVolumeCompare() //&& stock.getVolumeCompare() < 3* stock4.getVolumeCompare()
                        && stock.getAmplitude() >= stock2.getAmplitude() && stock.getAmplitude() >= stock4.getAmplitude()

                        && stock.getChangePercent()+stock2.getChangePercent() + stock4Map.get(key).getChangePercent() > 0
                ){
                    String title = "";
                    if(curVolumeCompare < 3* stock4.getVolumeCompare()){
                        title = "精选";
                    }
//                    String title = "";
//                    // if(stock.getPriceMin()< stock2.getPriceNow() && stock.getPriceNow() > stock2.getPriceNow() && stock4Map.get(key).getPriceNow() > stock2.getPriceNow()) {
//                    // if(stock4Map.get(key).getVolumeCompare()< stock2.getVolumeCompare()  && stock2.getChangePercent() > stock4Map.get(key).getChangePercent() && ( stock.getExchange()>5) && stock.getPriceMin() >= stock2.getPriceNow()) {
//                    //   if(stock2.getInPan() < stock2.getOutPan() && stock.getInPan()  < stock.getOutPan()) {//stock.getPriceNow() <= stock.getPriceAvg() &&                         && (stock.getOutPan() -stock.getInPan() > stock2.getOutPan() -stock2.getInPan())
//                    if(stock.getPriceMin()>stock2.getPriceNow()) {
//                        title = "精选";
//                    }
                    //   }
//                //    }
                    double profit =  0;
                    if(stock3Map.containsKey(key)){
                        profit = (((stock3Map.get(key).getPriceMax() - stock.getPriceNow()) / stock.getPriceNow()) * 100);
                    }
                    if(profit > 5){
                        title = "****"+title;
                    }
//                    System.out.println(title+"盈利" + profit + "---" + stock.getName());
                    stringBuffer.append(title+"盈利" + profit + "---" + stock.getName()+"\n");
                }
            });
            System.out.println(stringBuffer);
//            DingDingBot.send(stringBuffer.toString());
        }

    }
}
